import moment from "moment";
import { cloneDeep } from 'lodash';
// getToday() {
// 	return this.formatToDate(new Date());
// },
export const convertTextarea = (text: string) => {
	text = text || '';
	if (text) {
		text = text.replace(/\r\n/g, "<br>")
		text = text.replace(/\n/g, "<br>")
		//替换所有的空格（中文空格、英文空格都会被替换）
		text = text.replace(/\s/g, "&nbsp;")
	}
	return text
}
const textareaToHtml = (text: string) => {
	text = text || '';
	if (text) {
		text = text.replace(/\r\n/g, "<br>")
		text = text.replace(/\n/g, "<br>")
		//替换所有的空格（中文空格、英文空格都会被替换）
		text = text.replace(/\s/g, "&nbsp;")
	}
	return text
}

const round = (value: number, point = 2) => {
	value = Number(value)
	let a = Math.pow(10, point)
	return Math.round(value * a) / a || 0
}
const getProgressPercentage = (value: number) => {
	value = Number(value) || 0
	if (value > 1) return 100
	return Math.round(value * 100 * 100) / 100 || 0
}
//
const getProgress = (value: number) => {
	value = Number(value) || 0
	if (value > 1) return 100
	return Math.round(value * 100 * 100) / 100 || 0
}
const getNowDateString = () => {
	return toDateString(new Date());
}
const getNowDatetimeString = () => {
	return toDatetimeString(new Date());
}
const getNowShortDatetimeString = () => {
	return toShortDatetimeString(new Date());
}
//根据format格式化日期时间，返回字符串
const toDateStringByFormat = (value: any, format: string) => {
	if (!value) return ''
	let m = moment(value);
	if (!m.isValid()) {
		return "";
	}
	return m.format(format);
}
//返回YYYY-MM-DD格式的字符串
const toDateString = (value: any) => {
	return toDateStringByFormat(value, 'YYYY-MM-DD');
}
//返回YYYY-MM-DD HH:mm:ss格式的字符串
const toDatetimeString = (value: any) => {
	return toDateStringByFormat(value, 'YYYY-MM-DD HH:mm:ss');
}
//返回YYYY-MM-DD HH:mm格式的字符串
export const toShortDatetimeString = (value: any) => {
	return toDateStringByFormat(value, 'YYYY-MM-DD HH:mm');
}
//返回YYYY-MM-DD HH:mm格式的字符串
const toTimeString = (value: any) => {
	return toDateStringByFormat(value, 'HH:mm');
}
const copyByKey = (object: any, keys: Array<string>) => {
	let newObject: any = {}
	for (let key of keys) {
		newObject[key] = object[key]
	}
	return newObject
}
//根据传入的对象，返回一个没有空值的新对象
const removeNullKey = (obj: any) => {
	let newObj: any = {}
	for (let key of Object.keys(obj)) {
		if (obj[key] !== null && obj[key] !== '' && obj[key] !== undefined) {
			newObj[key] = obj[key]
		}
	}
	return newObj
}
export const objDeepCopy = (data: any): any => {
	//string,number,bool,null,undefined,symbol
	//object,array,date
	if (data && typeof data === "object") {
		//针对函数的拷贝
		if (typeof data === "function") {
			let tempFunc = data.bind(null);
			tempFunc.prototype = objDeepCopy(data.prototype);
			return tempFunc;
		}

		switch (Object.prototype.toString.call(data)) {
			case "[object String]":
				return data.toString();
			case "[object Number]":
				return Number(data.toString());
			case "[object Boolean]":
				return new Boolean(data.toString());
			case "[object Date]":
				return new Date(data.getTime());
			case "[object Array]":
				var arr = [];
				for (let i = 0; i < data.length; i++) {
					arr[i] = objDeepCopy(data[i]);
				}
				return arr;

			//js自带对象或用户自定义类实例
			case "[object Object]":
				var obj: any = {};
				for (let key in data) {
					//会遍历原型链上的属性方法，可以用hasOwnProperty来控制 （obj.hasOwnProperty(prop)
					obj[key] = objDeepCopy(data[key]);
				}
				return obj;
		}
	} else {
		//string,number,bool,null,undefined,symbol
		return data;
	}
}

const validateRules = {
	et0: (rule: any, value: any, callback: any) => {
		if (value <= 0) {
			callback(new Error('必须大于0'))
		} else {
			callback()
		}
	},
	num(rule: any, value: any, callback: any) {
		let regex = /^\d*\.?\d*$/;
		if (regex.test(value)) {
			callback();
		} else {
			callback("请输入数字");
		}
	},
	int(rule: any, value: any, callback: any) {
		let regex = /^\d*$/;
		if (regex.test(value)) {
			callback();
		} else {
			callback("请输入整数");
		}
	},
	createCheckExist(func: any, instance: any, idPath: string, message: string) {
		let paths = idPath.split(".");
		return (rule: any, value: any, callback: any) => {
			if (value) {
				let id = instance;
				paths.forEach(item => {
					id = id[item];
				});
				func(value, id).then(res => {
					if (res.data) {
						callback(new Error(message));
					} else {
						callback();
					}
				});
			} else {
				callback();
			}
		}
	}
	// createCheckPropUnique(method,form,message){
	// 	console.log(form)
	// 	return (rule,value,callback,a,b,c,d)=>{
	// 		console.log(form)
	// 		if(value){
	// 			method(value,form.id).then(res=>{
	// 				if(res.data){
	// 					callback()
	// 				}else{
	// 					callback(new Error(message))
	// 				}
	// 			})
	// 		}else{
	// 			callback()
	// 		}
	// 	}
	// }
}
export const toTreeData = (data: Array<any>, parentIdKey = "parentId", childrenKey = "children") => {
	let rootList: any = []
	data.forEach((item, index) => {
		if (!item[parentIdKey] || !data.some(i => item[parentIdKey] == i.id)) {
			rootList.push(item)
		}
	})
	function convertTree(treeData: Array<any>) {
		treeData.forEach(d => {
			data.forEach((item, index) => {
				if (item[parentIdKey] && item[parentIdKey] == d.id) {
					if (!d[childrenKey]) d[childrenKey] = []
					d.children.push(item)
				}
			})
			if (d[childrenKey]) convertTree(d[childrenKey])
		})
	}
	console.log(rootList)
	convertTree(rootList)
	return rootList
}
//传一个文件大小以字节为单位，返回一个对应单位的大小
const getFileSizeText = (fileSize) => {
	if (fileSize < 1024) {
		return fileSize + " Byte";
	}
	if (fileSize < 1024 * 1024) {
		return round(fileSize / 1024, 2) + " Kb";
	}
	if (fileSize < 1024 * 1024 * 1024) {
		return round(fileSize / 1024 / 1024, 2) + " Mb";
	}
	return round(fileSize / 1024 / 1024 / 1024, 2) + " Gb";
}


export const cloneDeepObject = (obj: any) => {
	return cloneDeep(obj)
}

export const cloneObjectValue = (targetObject: object, valueObject: object) => {
	for (let key of Object.keys(valueObject)) {
		if (Reflect.has(targetObject, key)) {
			let value = Reflect.get(valueObject, key);
			if (typeof value == "object") {
				value = cloneDeep(value)
			}
			Reflect.set(targetObject, key, value)
		}
	}
}

//移除没空值，并返回新的对象
export const removeObjectEmptyKey = (obj: Object) => {	
	return Object.fromEntries(
		Object.entries(obj).filter(([key, value]) => value !== null && value !== undefined && value !== "")
	);
}
